"""
---------------------------------------------------------------------
- File: service_users.py
- Date: 2025/11/17
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 相关用户业务逻辑
---------------------------------------------------------------------
"""

from sqlalchemy.orm import selectinload
from sqlmodel import select, or_

from app.core.security import get_password_hash
from app.models.system import Users
from app.schemas.system.users import UserCreate, UserUpdate
from .service_crud import CRUDBase


class ServiceUsers(CRUDBase[Users, UserCreate, UserUpdate]):

    # 相关用户业务逻辑方法
    async def get_by_user_no(self, *, user_no: int | str) -> Users | None:
        """
        根据用户编号获取用户信息
        """
        statement = select(self.model).where(self.model.user_no == user_no)
        result = await self.session.exec(statement)
        return result.first()

    async def get_by_user_name(self, *, user_name: str) -> Users | None:
        """
        根据用户名获取用户信息
        """
        statement = select(self.model).where(self.model.user_name == user_name)
        result = await self.session.exec(statement)
        return result.first()

    async def get_by_user_email(self, *, user_email: str) -> Users | None:
        """
        根据用户邮箱获取用户信息
        """
        statement = select(self.model).where(self.model.user_email == user_email)
        result = await self.session.exec(statement)
        return result.first()

    async def get_by_phone(self, *, user_phone: str) -> Users | None:
        """
        根据手机号获取用户信息
        """
        statement = select(self.model).where(self.model.user_phone == user_phone)
        result = await self.session.exec(statement)
        return result.first()

    # 检查用户是否存在
    async def get_existing_user(self, *, user_in: UserCreate) -> Users | None:
        """
        检查用户是否存在
        """
        statement = select(self.model).where(
            or_(
                self.model.user_no == user_in.user_no,
                self.model.user_name == user_in.user_name,
                self.model.user_email == user_in.user_email,
                self.model.user_phone == user_in.user_phone,
            )
        )
        result = await self.session.exec(statement)
        return result.first()

    # 重写create方法
    async def create(self, *, obj_in: UserCreate) -> Users:
        """
        创建用户
        """

        # 1. 模型数据转字典
        create_data = obj_in.model_dump()
        # 2. 删除password字段
        plain_password = create_data.pop("password")
        # 3. 加密密码
        hash_password = get_password_hash(plain_password)
        # 4. 创建数据库模型实例
        db_obj = self.model(**create_data, hash_password=hash_password)
        # 5. 保存到数据库
        self.session.add(db_obj)
        await self.session.commit()
        await self.session.refresh(db_obj)
        return db_obj

    async def get_multi_userWithRoles(self, *, skip: int = 0, limit: int = 10) -> list[Users]:
        """
        获取用户列表（包含角色信息）
        """
        statement = (
            select(self.model).options(selectinload(Users.roles)).order_by(self.model.id).offset(skip).limit(limit)
        )
        result = await self.session.exec(statement)
        return result.all()  # type: ignore
